import React, { useEffect, useState } from "react";
import {
  Card,
  Button,
  Table,
  Input,
  message,
  Form,
  Switch,
  Avatar,
  Modal,
} from "antd";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import axios from "axios";
import { connect } from "react-redux";

const User = (props) => {
  const { userInfo } = props;
  const [form] = Form.useForm();

  let [total, setTotal] = useState("");
  let [current, setCurrent] = useState(1);
  let [name, setName] = useState("");
  let [email, setEmail] = useState("");
  let [isLoading, setIsLoading] = useState(true);
  let [userList, setUserList] = useState([]);
  let [isModalVisible, setIsModalVisible] = useState(false);
  let [isModalEditVisible, setIsModalEditVisible] = useState(false);
  let [id, setId] = useState("");

  let [initName, setInitName] = useState("");
  let [initEmail, setInitEmail] = useState("");

  const reqUserList = async (current, name, email) => {
    try {
      const responce = await axios.get(
        "http://api.shop.eduwork.cn/api/admin/users",

        {
          params: { current: current, name: name, email: email },
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      isLoading = false;
      setIsLoading(isLoading);
      userList = responce.data.data;
      total = responce.data.meta.pagination.total;
      current = responce.data.meta.pagination.current_page;
      setUserList(userList);
      setTotal(total);
      setCurrent(current);
    } catch (err) {
      message.error(err.message);
    }
  };

  const updateCurrent = (number) => {
    current = number;
    setCurrent(current);
    reqUserList(current, name, email);
  };

  const updateStatus = async (id) => {
    const responce = await axios.patch(
      `http://api.shop.eduwork.cn/api/admin/users/${id}/lock`,

      {},
      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    if (responce.status === 204) {
      message.success("更新成功");
    } else {
      message.error("更新失败");
    }
  };

  const reqAddUser = async (values) => {
    try {
      const responce = await axios.post(
        "http://api.shop.eduwork.cn/api/admin/users",
        values,

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      if (responce.status === 201) {
        message.success("添加用户成功");
      }

      form.resetFields();
      setIsModalVisible(false);
    } catch (err) {
      message.error("用户名/邮箱格式/密码错误");
    }
  };

  const reqUpdateUser = async (values) => {
    try {
      const responce = await axios.put(
        `http://api.shop.eduwork.cn/api/admin/users/${id}`,
        values,

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      if (responce.status === 204) {
        message.success("更新用户信息成功");
      }

      form.resetFields();
      setIsModalEditVisible(false);
    } catch (err) {
      message.error("用户名/邮箱格式错误");
    }
  };

  useEffect(() => {
    reqUserList(current);
    // eslint-disable-next-line
  }, []);

  const onSearch = (values) => {
    setName(values.name);
    setEmail(values.email);
    reqUserList(current, values.name, values.email);
  };

  const showAdd = () => {
    setIsModalVisible(true);
  };

  const showEdit = (item) => {
    setInitName(item.name);
    setInitEmail(item.email);
    setId(item.id);
    setIsModalEditVisible(true);
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
  };

  const handleEditCancel = () => {
    form.resetFields();
    setIsModalEditVisible(false);
  };

  const columns = [
    {
      title: "头像",
      dataIndex: "avatar_url",
      key: "avatar_url",
      render: (avatar_url) => {
        return <Avatar src={avatar_url} />;
      },
    },
    {
      title: "用户名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "是否禁用",
      //dataIndex: "is_locked",
      align: "center",
      key: "is_locked",
      render: (item) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            defaultChecked={item.is_locked === 0 ? true : false}
            onChange={() => {
              updateStatus(item.id);
            }}
          />
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      align: "center",
      key: "created_at",
    },
    {
      title: "操作",
      // dataIndex: "created_at",
      align: "center",
      key: "operation",
      render: (item) => {
        return (
          <Button
            type="link"
            onClick={() => {
              showEdit(item);
            }}
          >
            编辑
          </Button>
        );
      },
    },
  ];

  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 4,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 16,
      },
    },
  };

  return (
    <div>
      <Card
        title={
          <Form name="horizontal_login" layout="inline" onFinish={onSearch}>
            <Form.Item name="name">
              <Input placeholder="Username" allowClear />
            </Form.Item>
            <Form.Item
              name="email"
              rules={[
                {
                  type: "email",
                  message: "The input is not valid E-mail!",
                },
              ]}
            >
              <Input placeholder="E-mail" allowClear />
            </Form.Item>
            <Form.Item shouldUpdate>
              {() => (
                <Button type="primary" htmlType="submit">
                  <SearchOutlined /> 搜索
                </Button>
              )}
            </Form.Item>
          </Form>
        }
        extra={
          <Button type="primary" onClick={showAdd}>
            <PlusOutlined />
            新建
          </Button>
        }
        loading={isLoading}
      >
        <Table
          dataSource={userList}
          columns={columns}
          rowKey="id"
          pagination={{
            pageSize: 10,
            total: total,
            current: current,
            onChange: updateCurrent,
            showQuickJumper: true,
          }}
        />
      </Card>

      <Modal
        title="新增用户"
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          form={form}
          name="addUser"
          {...formItemLayout}
          onFinish={reqAddUser}
        >
          <Form.Item
            name="name"
            label="用户名"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="E-mail"
            rules={[
              {
                type: "email",
                message: "The input is not valid E-mail!",
              },
              {
                required: true,
                message: "Please input your E-mail!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="password"
            label="Password"
            rules={[
              {
                required: true,
                message: "Please input your password!",
              },
            ]}
            hasFeedback
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              span: 12,
              offset: 4,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="修改用户信息"
        visible={isModalEditVisible}
        onCancel={handleEditCancel}
        footer={null}
      >
        <Form
          form={form}
          name="updateUser"
          {...formItemLayout}
          onFinish={reqUpdateUser}
          initialValues={{ name: initName, email: initEmail }}
        >
          <Form.Item
            name="name"
            label="用户名"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="E-mail"
            rules={[
              {
                type: "email",
                message: "The input is not valid E-mail!",
              },
              {
                required: true,
                message: "Please input your E-mail!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              span: 12,
              offset: 4,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default connect((state) => ({ userInfo: state.userInfo }))(User);
